package com.jstyle.jclife.activity;

import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;

import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;


import com.jstyle.blesdk.Util.SingleDealData;
import com.jstyle.blesdk.callback.DataListener;
import com.jstyle.blesdk.cmdenum.SendCmdState;
import com.jstyle.blesdk.model.DeviceBean;
import com.jstyle.blesdk.model.SendData;
import com.jstyle.blesdk.model.SetTime;
import com.jstyle.jclife.R;
import com.jstyle.jclife.app.MyApplication;
import com.jstyle.jclife.ble.BleManager;
import com.jstyle.jclife.ble.BleService;
import com.jstyle.jclife.fragment.HomePageFragment;
import com.jstyle.jclife.model.ActionData;
import com.jstyle.jclife.model.BleData;

import com.jstyle.jclife.utils.RxBus;
import com.jstyle.jclife.utils.SharedPreferenceUtils;
import com.jstyle.jclife.utils.UploadUtils;

import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;


/**
 * Created by Administrator on 2017/3/22.
 */

public class BaseActivity extends AppCompatActivity implements DataListener {
    private static final String TAG = "BaseActivity";
    protected static Toast toast;
    protected ProgressDialog progressDialog;
    private BluetoothAdapter mBluetoothAdapter;
    private int REQUEST_ENABLE_BT = 0;
    private Disposable subscription;
    private int filedCount;
    public static final String action_enterecg = "EnterEcg";
    protected InputMethodManager manager;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().requestFeature(Window.FEATURE_ACTIVITY_TRANSITIONS);
        }
        //     MyApplication.instance().setAppOrientation(this, MyApplication.instance());
        manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        subscribe();
    }



    protected boolean sendData(SendCmdState sendCmdState, SendData sendData) {
        if (!BleManager.getInstance().isConnected()) {
            //   showToast(getString(R.string.pair_device));
            return false;
        }
        if (sendData == null) {
            BleManager.getInstance().writeValue(SingleDealData.sendData(sendCmdState));
        } else {
            BleManager.getInstance().writeValue(SingleDealData.sendData(sendCmdState, sendData));
        }
        return true;
    }

    protected boolean offerData(SendCmdState sendCmdState, SendData sendData) {
        if (!BleManager.getInstance().isConnected()) {
            //   showToast(getString(R.string.pair_device));
            return false;
        }
        if (sendData == null) {
            BleManager.getInstance().offerValue(SingleDealData.sendData(sendCmdState));
        } else {
            BleManager.getInstance().offerValue(SingleDealData.sendData(sendCmdState, sendData));
        }
        return true;

    }

    protected boolean writeData(byte[] value) {
        if (!BleManager.getInstance().isConnected()) {
            //showToast(getString(R.string.pair_device));
            return false;
        }
        if (value != null) {
            BleManager.getInstance().writeValue(value);
        }
        return true;

    }

    protected boolean offerData(SendCmdState sendCmdState) {
        return offerData(sendCmdState, null);
    }

    protected void offerData(byte[] value) {
        BleManager.getInstance().offerValue(value);
    }

    protected void offerData() {
        BleManager.getInstance().writeValue();
    }

    protected boolean sendData(SendCmdState sendCmdState) {
        return sendData(sendCmdState, null);
    }

    protected void subscribe() {
        Log.i(TAG, "subscribe: " + getLocalClassName());
        RxBus.getInstance().toObservable(BleData.class).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<BleData>() {
            @Override
            public void onSubscribe(Disposable d) {
                subscription = d;
            }

            @Override
            public void onNext(BleData bleData) {

                String action = bleData.getAction();
                if (action.equals(BleService.ACTION_DATA_AVAILABLE)) {
                    byte[] value = bleData.getValue();
                    SingleDealData.receiveUpdateValue(value, BaseActivity.this);
                } else if (action.equals(BleService.ACTION_GATT_onDescriptorWrite)) {

                    onConnect();
                } else if (action.equals(BleService.ACTION_GATT_DISCONNECTED)) {
                    onDisconnect();
                } else if (OtaActivity.Action_Dfu_Failed.equals(action)) {
                    filedCount++;
                    if (filedCount == 5) {
                        filedCount = 0;
                        showToast(getString(R.string.dfu_failed));
                        String result = bleData.getData();
                        String fwVersion = SharedPreferenceUtils.getSpString(SharedPreferenceUtils.KEY_fwVersion);
                        UploadUtils.uploadOtaLogData(BaseActivity.this,
                                MyApplication.getJstyleDevice().getDeviceNo(), fwVersion, result);
                    } else {
                        Log.i(TAG, "accept: 升级失败重新升");
                        startOta();
                    }
                } else if (OtaActivity.Action_Dfu_Complete.equals(action)) {
                    // tvRecevice.append(getString(R.string.ota_success) + successCount + "\n");
                    filedCount = 0;
                    otaSuccess();
                } else if (HomePageFragment.ACTION_UPDATE_GOA.equals(action)) {
                    changeGoal();
                } else if (ActionData.FinishSignIn.equals(action)) {
                    finishSignIn();
                } else if (ActionData.FinishLoginIn.equals(action)) {
                    finishLoginIn();
                } else if (FileUpdateActivity.action_dfu_later.equals(action)) {
                    dfuLater();
                } else if (action_enterecg.equals(action)) {
                    enterEcg();
                } else if (ActionData.ActivateFinished.equals(action)) {
                    ActivateFinished();
                } else if (ActionData.ActivateUnFinished.equals(action)) {
                    ActivateUnFinished();
                } else if (ActionData.ChangeDevice.equals(action)) {
                    changeDevice();
                }


            }


            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    protected void finishLoginIn() {

    }

    private void enterEcg() {
        if (this instanceof MainActivity) {

        } else {
            finish();
        }
    }

    protected void dfuLater() {
    }

    protected void ActivateFinished() {
    }

    protected void ActivateUnFinished() {
    }

    protected void finishSignIn() {
        Log.i(TAG, "finishSignIn: ");
    }

    protected void changeGoal() {

    }

    ;

    protected void otaSuccess() {
    }

    protected void otaFailed() {
    }

    protected void startOta() {
    }

    protected void onConnect() {

    }

    protected void onDisconnect() {

    }

    public void sendTime() {

        SetTime setTime = new SetTime();
        // offerData(SendCmdState.READ_DEVICE_BATTERY);
        offerData(SendCmdState.SEND_DEVICE_Time, setTime);
        offerData();
    }

    protected void showStatusBar() {
    }

    protected void showToast(String text) {
        if (toast == null) {
            toast = Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT);
        } else {
            toast.setText(text);
        }
        toast.show();
    }

    public void showToastLong(String text) {
        if (toast == null) {
            toast = Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG);
        } else {
            toast.setText(text);
        }
        toast.show();
    }

    protected void startActivity(Class activity) {
        Intent intent = new Intent(this, activity);

        startActivity(intent);

    }

    protected void startActivity(Class activity, String key, int value) {
        Intent intent = new Intent(this, activity);
        intent.putExtra(key, value);
        startActivity(intent);
    }

    protected void startActivity(Class activity, String key, String value) {
        Intent intent = new Intent(this, activity);
        intent.putExtra(key, value);
        startActivity(intent);
    }

    protected void startActivity(Class activity, String key, boolean value) {
        Intent intent = new Intent(this, activity);
        intent.putExtra(key, value);
        startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unSubscribe(subscription);
    }

    public void showProgressDialog(String message) {
        if (isDestroyed()) return;
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(this, R.style.appprogressdialog);
        }
        if (progressDialog.isShowing()) return;
        progressDialog.setMessage(message);
        progressDialog.show();
    }

    protected void disMissProgressDialog() {
        if (isDestroyed()) return;
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }

    protected void disMissDialog(AlertDialog alertDialog) {
        if (isDestroyed()) return;
        if (alertDialog != null && alertDialog.isShowing()) {
            alertDialog.dismiss();
        }
    }

    protected void enableBle() {
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
    }

    protected boolean isBleEnable() {
        final BluetoothManager bluetoothManager =
                (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        if (bluetoothManager == null) return false;
        mBluetoothAdapter = bluetoothManager.getAdapter();
        return mBluetoothAdapter != null && mBluetoothAdapter.isEnabled();
    }

    protected void unSubscribe(Disposable subscription) {
        if (subscription != null && !subscription.isDisposed()) {
            subscription.dispose();
        }
    }

    @Override
    public void dataCallback(Map<String, String> maps, SendCmdState sendCmdState) {

    }

    @Override
    public void dataCallback(DeviceBean deviceBean, SendCmdState sendCmdState) {

    }

    protected void changeDevice() {

    }

    // //   protected boolean isJstyleFlavor(){
//        return BuildConfig.FLAVOR.equals("jstyle");
//    }
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            if (getCurrentFocus() != null
                    && getCurrentFocus().getWindowToken() != null) {
                manager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
        return super.onTouchEvent(event);
    }
}
